package cn.tedu.submarine;

import javax.swing.ImageIcon;
import java.awt.Graphics;
import java.util.Random;

public abstract class SeaObject {

    public static final int LIVE = 0;
    public static final int DEAD = 1;
    protected int state = LIVE;

    protected int width;
    protected int height;
    protected int x;
    protected int y;
    protected int speed;

    /* 给侦察潜艇，水雷潜艇，鱼雷潜艇提供构造 */
    public SeaObject(int width, int height) {
        this.width = width;
        this.height = height;
        x = -width;
        Random random = new Random();
        y = random.nextInt(World.HEIGHT - height - 150 + 1) + 150;
        speed = random.nextInt(4) + 1;
    }

    /* 给战舰，炸弹，水雷提供构造 */
    public SeaObject(int width, int height, int x, int y, int speed) {
        this.width = width;
        this.height = height;
        this.x = x;
        this.y = y;
        this.speed = speed;
    }

    /* 移动 */
    public abstract void move();

    /*获取图片*/
    public abstract ImageIcon getImage();

    /* 判断是否是活着的 */
    public boolean isLive() {
        return state == LIVE;
    }

    /* 判断是否是死了的 */
    public boolean isDead() {
        return state == DEAD;
    }

    /* 画对象   g：画笔 */
    public void paintImage(Graphics graphics) {
        if (this.isLive()) {
            this.getImage().paintIcon(null, graphics, this.x, this.y);
        }
    }

    /**
     * 检测潜艇是否越界
     *
     * @return 越界则ture，没越界则false
     */
    public boolean isOutOfBounds() {
        return this.x >= World.WIDTH;
    }

    /**
     * 检测是否碰撞
     *
     * @param other 另一个碰撞对象
     * @return 碰撞了返回true  没有碰撞就返回false
     */
    public boolean isHit(SeaObject other) {
        //假设this是潜艇，other是炸弹
        int x1 = this.x - other.width;
        int x2 = this.x + this.width;
        int y1 = this.y - other.height;
        int y2 = this.y + this.height;
        int x = other.x;
        int y = other.y;

        return x >= x1 && x <= x2 && y >= y1 && y <= y2;
    }

    public void goDead(){
        state = DEAD;
    }

}
